﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace PowerSys.SystemFramework.AOP
{
    public class AOPHelper
    {
        public delegate void MyMethod();
        public delegate void MyMethod<T>(T source);
        public delegate R MyMethod<T, R>(T source);

        public static SysMessage Do(MyMethod runMethod)
        {
            SysMessage message = new SysMessage();

            try
            {
                runMethod();
                message.Success = false;
                message.Code = 0;
                message.Name = "";
                message.Type = SysMessage.MessageType.Success;
                message.Detail = "";
                message.SysExcepton = null;
            }
            catch (Exception ex)
            {
                message.Success = true;
                message.Code = -1;
                message.Name = "";
                message.Type = SysMessage.MessageType.Error;
                message.Detail = runMethod.ToString();
                message.SysExcepton = ex;
            }
            return message;
        }

        /// <summary>
        /// 事务处理
        /// </summary>
        /// <param name="runMethods">方法序列</param>
        public static SysMessage DoWithTransaction(params MyMethod[] runMethods)
        {
            int i = 0;
            SysMessage message = new SysMessage();

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    for (i = 0; i < runMethods.Length; i++)
                    {
                        runMethods[i]();
                    }
                    scope.Complete();
                }

                message.Success = false;
                message.Code = 0;
                message.Name = "";
                message.Type = SysMessage.MessageType.Success;
                message.Detail = "";
                message.SysExcepton = null;
            }
            catch (Exception ex)
            {
                message.Success = true;
                message.Code = -1;
                message.Name = "";
                message.Type = SysMessage.MessageType.Error;
                message.Detail = runMethods[i].ToString();
                message.SysExcepton = ex;
            }
            return message;
        }
    }
}
